/*******include*********/
#include "BleConnectionStatus.h"
#include "BleKeyboard.h"
#include "KeyboardOutputCallbacks.h"
#include <Encoder.h>
#include <OneButton.h>
#ifdef __AVR__
  #include <avr/power.h>
#endif
/*******define*********/
#define pinA 8
#define pinB 4
#define pinSW 5
#define PIN_VIBRATOR 19 //振动
/****************/
BleKeyboard hid2Ble("ESP32C3Dial", "Xusir", 100);

/*******函数声明*********/
void send_ARR();
class Mycallback : public BLECharacteristicCallbacks
{

};
/*******旋钮部分*********/
Encoder myEnc(pinA, pinB);
OneButton button(pinSW, true, true);
long longpress_trigger = 0;
long vibe_until = 0;
int vibe_strength = 100;
void setup()
{
  Serial.begin(115200);
  pinMode(pinA,INPUT_PULLUP);//enable GPIO
  pinMode(pinB,INPUT_PULLUP);//enable GPIO
  pinMode(pinSW,INPUT_PULLUP);//enable GPIO
  button.attachClick(buttonClick);
  button.attachDuringLongPress(longPress);
  button.attachLongPressStop(longPressStop);
  hid2Ble.begin();
  pinMode(PIN_VIBRATOR, OUTPUT);
  digitalWrite(PIN_VIBRATOR, LOW);
}

void vibratorOn(){
  digitalWrite(PIN_VIBRATOR, HIGH);
}

void vibratorOff(){
  digitalWrite(PIN_VIBRATOR, LOW);
}
void vibratorCheck(){
  if (vibe_until > millis()){
    digitalWrite(PIN_VIBRATOR, HIGH);
  } else {
    digitalWrite(PIN_VIBRATOR, LOW);
  }
}

void buttonClick(){
    Serial.println("buttonClick");
    vibe_until = millis() + vibe_strength;
    vibratorCheck();
    hid2Ble.pressDial();
    hid2Ble.releaseDial();
}

void longPress(){
  if ( millis() - longpress_trigger > 400){
    Serial.println("longPress");
    vibe_until = millis() + vibe_strength*2;
    vibratorCheck();
    hid2Ble.pressDial();
    Serial.println("dialPressed");
    longpress_trigger = millis();
  }
}

void longPressStop(){
  hid2Ble.releaseDial();
  vibratorOff();
}

void loop()
{ 
 if (hid2Ble.isConnected())// if BLE Connected
 {
   vibratorCheck();
   send_ARR();//send Pushdata
   button.tick();
 }
}
long oldPosition  = 0;
int total = 0;
long threshold = 2;
void send_ARR(){

    long newPosition = myEnc.read();
    if (newPosition != oldPosition) {
      int d = oldPosition-newPosition;
      oldPosition = newPosition;
      Serial.print("d=");
      Serial.println(d);
      total += d;
      if(total>threshold){
        hid2Ble.rotate(1);
        total = 0;
      }else if(total<-threshold){
        hid2Ble.rotate(-1);
        total = 0;
      }
      if(total == 0){
        if (hid2Ble.dial_vibrate){
          vibe_until = millis() + vibe_strength;
          vibratorCheck();
        }  
      }
      Serial.println(newPosition);
    }
    
}
  
